<template>
    <div class="basic-tab-container">
        <!-- 客户基本信息 Group -->
        <el-card class="info-card" shadow="never">
            <template #header>
                <div class="card-header">
                    <div class="title-wrapper">
                        <span class="title-text">客户基本信息</span>
                        <el-tag :type="customer.enabled ? 'success' : 'danger'" size="small" class="status-tag">
                            {{ customer.enabled ? '启用' : '停用' }}
                        </el-tag>
                    </div>
                    <el-button type="primary" size="small" @click="showEditDialog" v-if="hasEditPermission">
                        编辑
                    </el-button>
                </div>
            </template>

            <el-descriptions :column="3">
                <el-descriptions-item label="客户名称">{{ customer.name || '-' }}</el-descriptions-item>
                <el-descriptions-item label="联系人">{{ customer.contactName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ customer.contactPhoneNumber || '-' }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ customer.email || '-' }}</el-descriptions-item>
                <el-descriptions-item label="城市">{{ customer.city || '-' }}</el-descriptions-item>
                <el-descriptions-item label="地址">{{ customer.address || '-' }}</el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">{{ customer.remark || '-' }}</el-descriptions-item>
            </el-descriptions>
        </el-card>

        <!-- 账户信息 Group -->
        <el-card class="finance-card" shadow="never">
            <template #header>
                <div class="card-header">
                    <div class="title-wrapper">
                        <span class="title-text">账户信息</span>
                    </div>
                    <el-button type="primary" size="small" @click="showEditDialog" v-if="hasEditPermission">
                        编辑
                    </el-button>
                </div>
            </template>

            <el-table :data="filterFundAccount(customer.fundAccount)" style="width: 100%" border>
                <el-table-column prop="name" label="账户名称" width="180"></el-table-column>

                <el-table-column prop="balance" label="账户余额" width="120">
                    <template #default="scope">
                        <span v-if="isMetalAccount(scope.row)">
                            {{ formatMetal(scope.row.balance) }}
                        </span>
                        <span v-else>
                            {{ formatCurrency(scope.row.balance) }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 编辑对话框  -->
        <customer-basic-info-dialog ref="editDialog" mode="edit" @submit="handleEditSubmit" />

    </div>
</template>

<script>
import { Customer } from '../../public/engine/targetOrg/customer'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import CustomerBasicInfoDialog from './customerBasicInfoDialog.vue'
import { ElMessage } from 'element-plus'
import { Util } from '../../public/utils/util'
import { AppTheme } from '../../public/theme/appTheme'
import { FundAccountInsideType } from '../../public/engine/common/fundDefinition'


export default {
    name: 'CustomerBasicTabPage',
    components: {
        CustomerBasicInfoDialog
    },
    props: {
        customerId: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            customer: new Customer(),
            receivableAmount: 0,
            payableAmount: 0,
            lastTransactionDate: '',
            creditLimit: 0,
            showEditDialogVisible: false,
            fundColor: AppTheme.foundStringColor,
            metalColor: AppTheme.foundStringBlueColor,
            loading: false,
        }
    },
    computed: {
        hasEditPermission() {
            // 根据实际权限系统调整
            return true
        },


    },
    async created() {
        await this.loadCustomerData()
        await this.loadFinancialData()
    },
    methods: {
        async loadCustomerData() {
            try {
                this.loading = true
                const res = await new BasicUiAction().getCustomerDetailInfo(this.customerId)
                if (res) {
                    this.customer = res
                }
            } catch (error) {
                console.error('加载客户数据失败:', error)
                ElMessage.error('加载客户数据失败')
            } finally {
                this.loading = false
            }
        },
        async loadFinancialData() {
            try {
                // 模拟财务数据 - 替换为实际API调用
                this.receivableAmount = 12500.78
                this.payableAmount = 5800.32
                this.lastTransactionDate = '2023-06-15'
                this.creditLimit = 50000
            } catch (error) {
                console.error('加载财务数据失败:', error)
            }
        },
        formatCurrency(value) {
            return `¥${value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`
        },
        formatMetal(value) {
            return `${value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')} 克`
        },
        showEditDialog() {
            console.log('Opening dialog') // 添加调试日志
            // 通过 ref 调用子组件的 open 方法
            this.$refs.editDialog.open(this.customer);
        },

        handleEditSubmit({ type, data }) {
            if (type === 'update') {
                ElMessage.success('客户信息更新成功')
                this.loadCustomerData() // 刷新数据

                // 通知detail page
                this.$emit('basicInfoUpdated', this.customer);
            }
        },

        isMetalAccount(fundAccount) {

            if (fundAccount && fundAccount.accountType && fundAccount.accountType.code === FundAccountInsideType.ObjMetalAccount.code) {
                return true;
            }
            return false;
        },

        ignoreAccount(fundAccount) {

            if (fundAccount && fundAccount.accountType && fundAccount.accountType.code === FundAccountInsideType.ObjFundAccount.code) {
                fundAccount.name = "存欠款";
            }

            if (fundAccount && fundAccount.accountType &&
                (fundAccount.accountType.code === FundAccountInsideType.AdvReceiveAccount.code || fundAccount.accountType.code === FundAccountInsideType.AdvPaymentAccount.code)) {
                return true;
            }
            return false;
        },

        filterFundAccount(fundAccountList) {
            return fundAccountList.filter(fundAccount => !this.ignoreAccount(fundAccount));
        }
    }
}
</script>

<style scoped>
.basic-tab-container {
    padding: 10px;
}

.customer-detail-container {
    padding: 20px;
    max-width: 1000px;
    /* 保留最大宽度限制 */
    margin-right: auto;
    /* 改为右侧自动，实现左对齐 */
}

.info-card {
    margin-bottom: 20px;
    min-width: 800px;
    max-width: 100%;
    border-radius: 10px;
    /* 添加圆角效果 */
}

.finance-card {
    margin-bottom: 20px;
    min-width: 800px;
    max-width: 100%;
    border-radius: 8px;
    /* 添加圆角效果 */
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

}

.title-wrapper {
    display: flex;
    align-items: center;
    gap: 18px;
}

.title-text {
    font-size: 16px;
    font-weight: bold;
}

.status-tag {
    margin-left: 0;
    font-size: 12px;
}

.amount {
    font-weight: bold;
    color: v-bind(fundColor);
    /* 使用JavaScript变量 */
}

.metailAmount {
    font-weight: bold;
    color: v-bind(metalColor);
    /* 使用JavaScript变量 */
}

.metalAmount {
    font-weight: bold;
    color: #409EFF;
}

.finance-card .el-descriptions-item {
    padding: 12px 10px;
}

.finance-content {
    padding: 12px;
}

.finance-row {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.finance-label {
    flex: 0 0 120px;
    /* 固定标签宽度 */
    text-align: left;
    font-weight: normal;
    color: #606266;
}
</style>